package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneException;
import com.atguigu.gulimall.member.exception.UserNameException;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberUserRegistVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;
import org.springframework.transaction.annotation.Transactional;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    //注册会员
    @Transactional()
    @Override
    public void regist(MemberUserRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        //默认等级
        MemberLevelEntity memberLevelEntity = this.baseMapper.selectLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());
        //判断用户名、手机号是否唯一
        Integer usernameCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", vo.getUserName()));
        if (usernameCount > 0){
            throw new UserNameException();
        }
        memberEntity.setUsername(vo.getUserName());
        Integer phoneCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", vo.getPhone()));
        if (phoneCount > 0){
            throw new PhoneException();
        }
        memberEntity.setMobile(vo.getPhone());
        //密码md5盐值加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);

        memberEntity.setGender(0);
        memberEntity.setCreateTime(new Date());
        this.baseMapper.insert(memberEntity);
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        //登陆账户为用户名或手机号，并且唯一
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        MemberEntity member = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                .or().eq("mobile", loginacct));
        //密码校验
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(password, member.getPassword());
        if (matches){
            return member;
        }else {
            return null;
        }
    }


    /**
     * 判断账号是否是第一次登陆
     * 1.查询uid(created_at) 是否存在，uid存在则表示不是第一次登陆，只需要更新access_token即可
     * 2.如果uid不存在，则查询第三方授权的用户信息，将用户信息、uid、access_token存入member服务
     * 3.返回MemberEntity
     */
    @Override
    public MemberEntity oauth2Login(SocialUser socialUser) throws Exception {
        //获取gitee授权用户的资料 https://gitee.com/api/v5/user
        //String host, String path, String method,
        //Map<String, String> headers,
        //Map<String, String> quer
        MemberEntity oatuthMemberEntity = null;
        String giteeId = null;
        String giteeName = null;
        try {
            Map<String,String> map = new HashMap<>();
            map.put("access_token",socialUser.getAccess_token());
            HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "GET", new HashMap<>(), map);
            oatuthMemberEntity = new MemberEntity();
            giteeId = "";
            giteeName = "";
            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = response.getEntity();
                String s = EntityUtils.toString(entity);
                JSONObject jsonObject = JSON.parseObject(s);
                giteeId = jsonObject.getString("id");
                giteeName = jsonObject.getString("name");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //判断账号是否是第一次登陆
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", giteeId));
        if (memberEntity != null){
            //uid存在,表示不是第一次登陆，则更新token即可
            MemberEntity member = new MemberEntity();
            member.setId(memberEntity.getId());
            member.setAccessToken(socialUser.getAccess_token());
            member.setExpiresIn(Long.toString(socialUser.getExpires_in()));
            this.baseMapper.updateById(member);
            //返回MemberEntity
            return memberEntity;
        }else {
            //查询为空表示是第一次登陆，根据第三方提供的api查询用户信息，然后注册
            oatuthMemberEntity.setSocialUid(giteeId);
            oatuthMemberEntity.setUsername(giteeName);
            oatuthMemberEntity.setCreateTime(new Date());
            oatuthMemberEntity.setAccessToken(socialUser.getAccess_token());
            oatuthMemberEntity.setExpiresIn(Long.toString(socialUser.getExpires_in()));
            this.baseMapper.insert(oatuthMemberEntity);
            return oatuthMemberEntity;
        }
    }


}